<route lang="json5">
{
  style: {
    navigationBarTitleText: '相册详情'
  }
}
</route>

<script lang="ts" setup>
import type { Photo } from '@/types/couple'
import dayjs from 'dayjs'
import { computed, onMounted, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useToast } from 'wot-design-uni'
import { useSupabaseCoupleStore } from '@/store/supabaseCouple'

defineOptions({ name: 'AlbumDetail' })

const coupleStore = useSupabaseCoupleStore()
const { success: showSuccess } = useToast()

const albumId = ref('')
// 待上传的本地临时图片
const pendingPhotos = ref<string[]>([])

// 从 store 获取相册数据
const album = computed(() => coupleStore.albums.find(a => a.id === albumId.value))
const photos = computed(() => album.value?.photos || [])

async function compressImageMp(path: string, quality = 70): Promise<string> {
  return await new Promise<string>((resolve, reject) => {
    uni.showLoading({ title: '压缩中...', mask: true })
    uni.compressImage({
      src: path,
      quality,
      success: (res) => {
        const out = (res as any).tempFilePath || path
        resolve(out)
      },
      fail: reject,
    })
  })
}

async function uploadToAlbumsBucket(localPath: string): Promise<string> {
  const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
  const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
  const compressed = await compressImageMp(localPath, 70)
  const ext = compressed.substring(compressed.lastIndexOf('.')) || localPath.substring(localPath.lastIndexOf('.'))
  const name = `album-${Date.now()}${ext}`
  const uploadUrl = `${supabaseUrl}/storage/v1/object/albums/${encodeURIComponent(name)}`
  await new Promise<void>((resolve, reject) => {
    const task = uni.uploadFile({
      url: uploadUrl,
      filePath: compressed,
      name: 'file',
      header: {
        'Authorization': `Bearer ${supabaseAnonKey}`,
        'Cache-Control': '3600',
        'x-upsert': 'false',
      },
      success: (res) => {
        if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300)
          resolve()
        else reject(new Error(`上传失败: ${res.statusCode}`))
      },
      fail: reject,
    })
    task.onProgressUpdate?.((p) => {
      uni.showLoading({ title: `上传中 ${p.progress}%`, mask: true })
    })
  })
  // 上传完成，确保关闭 loading
  uni.hideLoading()
  return `${supabaseUrl}/storage/v1/object/public/albums/${encodeURIComponent(name)}`
}

// 选择图片（与 moments 一致）
async function handleChooseImage() {
  const current = pendingPhotos.value.length
  if (current >= 9)
    return
  try {
    const res: any = await uni.chooseMedia({
      count: 9 - current,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
    })
    const paths = (res?.tempFiles || []).map((f: any) => f.tempFilePath)
    pendingPhotos.value.push(...paths)
  }
  catch {}
}

function handleRemovePending(index: number) {
  pendingPhotos.value.splice(index, 1)
}

async function addToAlbum() {
  if (!albumId.value || pendingPhotos.value.length === 0)
    return
  // 批量上传本地临时路径到 albums bucket
  const uploaded: string[] = []
  for (const p of pendingPhotos.value) {
    const url = await uploadToAlbumsBucket(p)
    uploaded.push(url)
  }
  for (const url of uploaded) {
    await coupleStore.addPhotoToAlbum(albumId.value, {
      url,
      title: '',
      description: '',
      location: '',
      tags: [],
      takenAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    })
  }
  pendingPhotos.value = []
  showSuccess('照片已添加到相册')
}

function preview(current: string) {
  // 过滤掉可能有权限问题的本地图片，只保留网络图片
  // 但保留头像等静态资源图片的显示
  const validUrls = photos.value.map(p => p.url).filter(url => url.startsWith('http'))
  const validCurrent = current.startsWith('http') ? current : validUrls[0]

  if (validUrls.length === 0) {
    showSuccess('暂无可预览的图片')
    return
  }

  uni.previewImage({
    current: validCurrent,
    urls: validUrls,
    fail: (err) => {
      console.error('图片预览失败:', err)
      showSuccess('图片预览失败')
    },
  })
}

function removePhoto(photo: Photo) {
  uni.showModal({
    title: '删除确认',
    content: '确定删除这张照片吗？',
    success: async ({ confirm }) => {
      if (confirm && albumId.value) {
        await coupleStore.removePhotoFromAlbum(albumId.value, photo.id)
        showSuccess('照片已删除')
      }
    },
  })
}

// 使用 onLoad 生命周期获取路由参数
onLoad((options: any) => {
  if (options.id) {
    albumId.value = options.id
  }
})

onMounted(() => {
  // 确保数据已加载
  if (!coupleStore.profile) {
    coupleStore.initProfile()
  }

  // 如果没有通过路由传递ID，则尝试使用第一个相册的ID
  if (!albumId.value && coupleStore.albums.length > 0) {
    albumId.value = coupleStore.albums[0].id
  }
})
</script>

<template>
  <view class="detail-container">
    <view class="header">
      <view class="title">
        {{ album?.title || '相册详情' }}
      </view>
      <view class="photo-uploader" style="margin-top:8px">
        <view class="photo-grid">
          <view v-for="(p, idx) in pendingPhotos" :key="idx" class="photo-item">
            <image :src="p" class="preview-img" mode="aspectFill" @click="preview(p)" />
            <view class="remove-icon" @click="handleRemovePending(idx)">
              <wd-icon name="close-bold" color="#fff" />
            </view>
          </view>
          <view v-if="pendingPhotos.length < 9" class="add-photo-btn" @click="handleChooseImage">
            <wd-icon name="add" size="36px" color="#ccc" />
          </view>
        </view>
      </view>
      <wd-button style="margin-top:8px" type="primary" size="small" :disabled="!pendingPhotos.length" @click="addToAlbum">
        添加到相册
      </wd-button>
    </view>

    <view class="grid">
      <view v-for="p in photos" :key="p.id" class="photo-item">
        <image :src="p.url" class="photo" mode="aspectFill" @click="preview(p.url)" />
        <view class="photo-actions">
          <wd-button size="small" plain @click="removePhoto(p)">
            删除
          </wd-button>
        </view>
      </view>
    </view>

    <view v-if="photos.length === 0" class="empty">
      <wd-icon name="picture" size="64px" color="#ccc" />
      <text class="tip">还没有照片，先上传几张吧～</text>
    </view>
  </view>
</template>

<style scoped lang="scss">
.detail-container {
  min-height: 100vh;
  background: #f5f5f5;
}
.header {
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #eee;
}
.title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}
.grid {
  padding: 12px 16px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 6px;
}
.photo-item {
  position: relative;
}
.photo {
  width: 100%;
  height: 110px;
  border-radius: 8px;
}
.photo-actions {
  position: absolute;
  top: 4px;
  right: 4px;
}
.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 0;
  color: #999;
}
.tip {
  margin-top: 8px;
  font-size: 12px;
}

/* 与 moments 页一致的上传预览样式 */
.photo-uploader {
  margin-top: 8px;
}
.photo-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}
/* 仅作用于顶部上传区域的预览项，避免影响下方已存在照片网格 */
.photo-uploader .photo-item {
  position: relative;
  width: 100%;
  padding-top: 100%;
  border-radius: 8px;
  overflow: hidden;
  background: #f7f7f7;
}
.preview-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.remove-icon {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.35);
  display: flex;
  align-items: center;
  justify-content: center;
}
.add-photo-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100px;
  border-radius: 8px;
  border: 1px dashed #ddd;
  background: #fafafa;
}
</style>
